package com.teatrace.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.teatrace.model.base.Device;
import com.teatrace.model.base.Employee;
import com.teatrace.model.pack.BoxProduct;
import com.teatrace.model.pack.GoodsType;
import com.teatrace.model.pack.PackingFlow;
import com.teatrace.model.pack.PackingType;
import com.teatrace.model.pack.ParticleProduct;
import com.teatrace.model.process.SemiFinishedProductPackage;
import com.teatrace.service.ServiceContext;
import com.teatrace.service.basic.BasicService;
import com.teatrace.service.pack.PackService;

public class PackAction extends ActionSupport implements RequestAware , SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(BasicAction.class);
	
	private Map<String, Object> req;
	private Map<String, Object> session;
	private PackService packService;
	private BasicService service;
	private String deviceName;
	private String empName;
	private int page = 1;
	private int selected; //标志那个标签被选中
	/**
	 * 这四个变量是为了接受工序名称
	 */
	private String process0;
	private String process1;
	private String process2;
	private String process3;
	private String process4;
	/**
	 * checkboxPar 这是保存粒子包的编号
	 */
	@SuppressWarnings("unchecked")
	private List checkboxPar;
	/**
	 * particalNums
	 */
	private String particalNums;
	private GoodsType goodsType;
	private PackingFlow packingFlow;
	private PackingType packingType;
	private ParticleProduct particleProduct;
	private BoxProduct boxProduct;
	private SemiFinishedProductPackage semifinishedProductPackage;
	
	public PackAction() {
		service = ServiceContext.getService(BasicService.class);
		packService = ServiceContext.getService(PackService.class);
	}
	
	/**
	 * 增加包装流程
	 * @return
	 * @throws Exception
	 */
	public String addPackingFlow() throws Exception {
		try{
			String desc = "";
			System.out.println("addPackingFlow enter action OK!");
			if(process1 != "" && process1 != null) {
				System.out.println("process1 : " + process1);
				desc = process1;
			}
			if(process2 != ""&&process2 != null){
				System.out.println("process2 : " + process2);
				desc  = desc + "-->" + process2;
			}
			if(process3 != null && process3 != ""){
				System.out.println("process3 : " + process3);
				desc += "-->" + process3;
			}
			if(process4 != null && process4 != ""){
				System.out.println("process4 : " + process4);
				desc += "-->" + process4;
			}
			int typeId = goodsType.getId();
			if(0 == typeId) {
				goodsType.setId(1);
			}
			else if(1 == typeId) {
				goodsType.setId(2);
			}else if(2 == typeId) {
				goodsType.setId(3);
			}
			packingFlow.setDescription(desc);
			packingFlow.setGoodsTypeId(goodsType.getId());
			service.add(packingFlow);
			listFlows();
			req.put("selected", typeId);//这是为了设置tab标签的selected
		}
		catch (Exception e) {
			log.error(e, e);
			return "FAIL";
		}
		return "addPackingFlow";
	}
	
	/**
	 * 修改包装流程时，
	 * 从list的jsp跳到update的jsp时，中间为了
	 * 处理数据，所以要跳到一个action进行处理
	 */
	public String updatePackingFlowTo() throws Exception{
		try {
			packingFlow = service.getById(PackingFlow.class, packingFlow.getPackingFlowId());
			System.out.println("有什么工序组成：" + packingFlow.getDescription());
			String desc = packingFlow.getDescription();
			int gTypeId = packingFlow.getGoodsTypeId();
			List<String> pcslist = new ArrayList<String>();
			String[] dps = desc.split("-->");
			for(String str : dps){
				pcslist.add(str);
				//System.out.println("str : " + str);
			}
			req.put("processList", pcslist);
			req.put("packingFlow", packingFlow);
			req.put("gTypeId", gTypeId);
		}catch(Exception ex){
			log.error(ex, ex);
			return "FAIL";
		}
		return "updatePackingFlowTo";
		//return "SUCCESS";
	}
	
	/**
	 * 修改包装流程
	 * @return
	 */
	public String updatePackingFlow()throws Exception{
		try {
			String desc = "";
			int typeId = goodsType.getId();
			if(process0 != "" && process0 != null) {
				System.out.println("process0: " + process0);
				desc = process0;
			}
			if(process1 != "" && process1 != null){
				System.out.println("process1: " + process1);
				desc  = desc + "-->" + process1;
			}
			if(process2 != null && process2 != ""){
				System.out.println("process2: " + process2);
				desc += "-->" + process2;
			}
			if(process3 != null && process3 != ""){
				System.out.println("process3: " + process3);
				desc += "-->" + process3;
			}
			packingFlow.setDescription(desc);
			packingFlow.setGoodsTypeId(typeId);
			service.update(packingFlow);
			listFlows();
			req.put("selected", typeId - 1);//这是为了设置tab标签的selected
		} catch (Exception e) {
			log.error(e, e);
			return "FAIL";
		}
		return "updatePackingFlow";
	}
	
	/**
	 * 以下为del 包装流程的方法
	 * @return
	 * @throws Exception
	 */
	public String delPackingFlow() throws Exception {
		try {
			packingFlow = service.getById(PackingFlow.class, packingFlow.getPackingFlowId());
			int typeId = packingFlow.getGoodsTypeId();
			System.out.println("typeId : " + typeId);
			//因为主键为字符类型，所以用不了逻辑删除
			//service.logicDeleteById(PackingFlow.class, packingFlow.getPackingFlowId());
			//如果有别的包装用了次流程，会抛异常，不能删除
			service.deleteById(PackingFlow.class, packingFlow.getPackingFlowId());
			listFlows();
			req.put("selected", (typeId - 1));//这是为了设置tab标签的selected
		} catch (Exception e) {
			log.error(e, e);
			return "FAIL";
		}
		return "delPackingFlow";
	}
	
	/**
	 * 列出包装流程
	 * @return
	 * @throws Exception 
	 */
	public String listPackingFlow() throws Exception {
		try {
			listFlows();
			req.put("selected", 0);//这是为了设置tab标签的selected
		}catch (Exception e) {
			log.error(e,e);
			return "FAIL";
		}
		return "listPackingFlow";
	}
	
	/**
	 * 流程列表时，提取重复的代码，
	 * 是一起把流程信息全都取出，
	 * 然后分成三个list传到页面
	 */
	private void listFlows() throws Exception{
		List<PackingFlow> list = new ArrayList<PackingFlow>();
		List<PackingFlow> list0 = new ArrayList<PackingFlow>();
		List<PackingFlow> list1 = new ArrayList<PackingFlow>();
		List<PackingFlow> list2 = new ArrayList<PackingFlow>();
		//list = packService.listObject(PackingFlow.class);
		list = service.listByPage(PackingFlow.class, 1);
		System.out.println("listSizePackingFlow :: " + list.size());
		for(PackingFlow pf : list) {
			if(1 == pf.getGoodsTypeId()) {
				list0.add(pf);
			}
			if(2 == pf.getGoodsTypeId()) {
				list1.add(pf);
			}
			if(3 == pf.getGoodsTypeId()) {
				list2.add(pf);
			}
		}
		req.put("listPackingFlow0", list0);
		req.put("listPackingFlow1", list1);
		req.put("listPackingFlow2", list2);
	}
	
	/***
	 * 以上为包装流程
	 * 以下为包装过程
	 */
	
	/**
	 * 商品类别
	 * 从left.jsp 跳转到 PackOption.jsp
	 * 每种商品类别的所有流程下来能够获得商品名称
	 * @return
	 * @throws Exception
	 */
	public String listPackGoodName() throws Exception {
		try {
			System.out.println("enter action OK ");
			listFlows();
		}catch (Exception e) {
			log.error(e, e);
			return "FAIL";
		}
		return "packGoodName";
	}
	
	/**
	 * 列出包装原料
	 * @return
	 * @throws Exception 
	 */
	public String listSemifinishedProductPackage() throws Exception{
		try {
			System.out.println("listSemifinishedProductPackage enter action OK");
			String id = packingFlow.getPackingFlowId();
			listSemiParBox(id);
	//		req.put("total", PageHelper.getTotalPage(service.count(SemiFinishedProductPackage.class)));
			req.put("total", 1);
			req.put("page", 1);
			req.put("selected", 0);
		} catch (Exception e) {
			log.error(e,e);
			return "FAIL";
		}
		return "listSemiFinishedProductPackage";
	}
	
	/**
	 * 中间代码《分别显示三个阶段的产品》
	 * 因为无论每一个步的包装然后显示列表，都要全部显示
	 * 而且每个操作都是一样的
	 * @param id
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked" })
	private void listSemiParBox(String id) throws Exception {
		packingFlow = service.getById(PackingFlow.class, id);
		String godName = packingFlow.getGoodsName();
		System.out.println(packingFlow.getDescription());
		String[] strDesc = packingFlow.getDescription().split("-->");
		List<String> descList = new ArrayList<String>();
		for(String str : strDesc) {
			descList.add(str);
		}
		req.put("descList", descList);
		req.put("packingFlowId", id);
		List tempList = new ArrayList();
		List<SemiFinishedProductPackage> listsfpp = packService.listObject(SemiFinishedProductPackage.class);
		for(SemiFinishedProductPackage sfp : listsfpp) {
			System.out.println("listsfpp: " + sfp.getTeaType());
			if(sfp.getTeaType() == null || sfp.getTeaType() == "") {
				tempList.add(sfp);
			}
		}
		System.out.println("tempList : " + tempList.size());
		listsfpp = tempList;
		req.put("godName", godName);
		req.put("listSemiFinishedProductPackage", listsfpp);
		
		List<ParticleProduct> listPar = service.listByCriteria(ParticleProduct.class, "isPar", 0);
		req.put("listPar", listPar);
		
		List<BoxProduct> listBox = packService.listObject(BoxProduct.class);
		req.put("listBox", listBox);
	}
	
	/**
	 * 第一：从加工出来的半成品经过粒子包装后
	 * 第二：返回到粒子列表，可以查看结果
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public String listParProduct() throws Exception {
		System.out.println("listParticleProduct enter action OK");
		try {
			String packingFlowId = packingFlow.getPackingFlowId();
			long id = semifinishedProductPackage.getId();
			System.out.println("packingFlowId : " + packingFlowId);
			System.out.println("semifinishedProductPackage : " + id);
			
			//更新SemifinishedProductPackage
			List<PackingFlow> packList = service.listByCriteria(PackingFlow.class, "packingFlowId", packingFlowId);
			List<SemiFinishedProductPackage> semiList = service.listByCriteria(SemiFinishedProductPackage.class, "Id", id);
			semifinishedProductPackage = semiList.get(0);
			semifinishedProductPackage.setPackingFlow(packList.get(0));
			semifinishedProductPackage.setTeaType(packList.get(0).getGoodsName());
			service.update(semifinishedProductPackage);
			
			//增加粒子包的产品
			String[] parIds = particalNums.split(",");
			System.out.println("parIds : " + parIds.length);
			
			HashSet emphs = new HashSet();
			HashSet devicehs = new HashSet();
			List<Employee> empLi = new ArrayList<Employee>();
			List<Device> deviceLi = new ArrayList<Device>();
			
			empLi = service.listByCriteria(Employee.class, "name", empName);
			System.out.println("empLi.get(0).getId(): " + empLi.get(0).getId());
			emphs.add(empLi.get(0));
			
			deviceLi = service.listByCriteria(Device.class, "name", deviceName);
			System.out.println("deviceLi.get(0).getId() : " + deviceLi.get(0).getId());
			devicehs.add(deviceLi.get(0));
			
			for(String str : parIds) {
				System.out.println("Str : " + str);
				particleProduct.setParticleProductId(Integer.parseInt(str));
				particleProduct.setIsPar(0);
				particleProduct.setSemifinishedProductPackageId(id);
				particleProduct.setEmps(emphs);
				particleProduct.setDevices(devicehs);
				service.add(particleProduct);
			}
			listSemiParBox(packingFlowId);
			req.put("total", 1);
			req.put("page", 1);
			req.put("selected", 1);
		} catch (Exception e) {
			log.error(e,e);
			return "FAIL";
		}
		return "listParProduct";
	}
	
	/**
	 * 半成品要进行第二步包装时，由多个小包变成一个中包或者大包
	 * 中间要记录所有的小包编号
	 * 所以把这些编号放到session里
	 * 为了下次一起提交数据
	 * @return
	 * @throws Exception
	 */
	public String semiDataLists() throws Exception {
		System.out.println("enter semiDateList OK : ");
		try{
			for(int i = 0 ; i < checkboxPar.size(); i ++) {
				System.out.println(checkboxPar.get(i));
			}
			if(null != session.get("checkboxPar")) {
				session.remove("checkboxPar");
			}
			session.put("checkboxPar", checkboxPar);
		}catch (Exception e) {
			log.error(e,e);
			return "FAIL";
		}
		return "semiDataList";
	}
	
	/**
	 * 第一：由多变一的包装
	 * 第二：列出最终产品
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public String listBoxProduct() throws Exception {
		try {
			System.out.println("listBoxProduct enter action OK");
			
			//把所包装的粒子包就在一个set类型
			checkboxPar = (List) session.get("checkboxPar");
			HashSet<ParticleProduct> parSet = new HashSet<ParticleProduct>();
			for(int i = 0 ; i < checkboxPar.size(); i ++) {
				System.out.println(i +" 个 "+ checkboxPar.get(i));
				particleProduct = service.getById(ParticleProduct.class, Integer.parseInt(checkboxPar.get(i).toString()));
				//要改变原来的particleProduct的状态 isPar 置1;
				particleProduct.setIsPar(1);
				//service.update(particleProduct);
				parSet.add(particleProduct);
			}
			//是要通过packingFlowId 来列出表
			long semiId = particleProduct.getSemifinishedProductPackageId();
			System.out.println("SemiId : " + semiId);
			semifinishedProductPackage = service.getById(SemiFinishedProductPackage.class, semiId);
			
			String packingFlowId = semifinishedProductPackage.getPackingFlow().getPackingFlowId();
			System.out.println("packingFlowId : " + packingFlowId);
			//packingFlow = semifinishedProductPackage.getPackingFlow();
			//String godName = packingFlow.getGoodsName();
			//System.out.println("packing : " + packingFlow.getGoodsName());
			//add boxProduct -----
			HashSet emphs = new HashSet();
			HashSet devicehs = new HashSet();
			List<Employee> empLi = new ArrayList<Employee>();
			List<Device> deviceLi = new ArrayList<Device>();
			
			empLi = service.listByCriteria(Employee.class, "name", empName);
			System.out.println("empLi.get(0).getId(): " + empLi.get(0).getId());
			emphs.add(empLi.get(0));
			
			deviceLi = service.listByCriteria(Device.class, "name", deviceName);
			System.out.println("deviceLi.get(0).getId() : " + deviceLi.get(0).getId());
			devicehs.add(deviceLi.get(0));
			boxProduct.setEmps(emphs);
			boxProduct.setDevices(devicehs);
			boxProduct.setParticleProducts(parSet);
			//service.add(boxProduct);
			listSemiParBox(packingFlowId);
			req.put("total", 1);
			req.put("page", 1);
			//req.put("goodName", godName);
			req.put("selected", 2);
		} catch (Exception e) {
			log.error(e,e);
			return "FAIL";
		}
		return "listBoxProduct";
	}
	
	/**
	 * 逻辑删除粒子产品
	 * @return
	 * @throws Exception
	 */
	public String delParticle() throws Exception{
		System.out.println("delParticle enter");
		try {
			System.out.println(" particleProductId :  "+particleProduct.getParticleProductId());
			service.logicDeleteById(ParticleProduct.class, particleProduct.getParticleProductId());
		}catch (Exception e) {
			log.error(e,e);
			return "FAIL";
		}
		return "SUCCESS";
	}
	
	public String delBox() throws Exception {
		System.out.println("delBox enter");
		try {
			System.out.println("boxProductId : "+boxProduct.getBoxProductId());
			service.logicDeleteById(BoxProduct.class, boxProduct.getBoxProductId());
		}catch (Exception e) {
			log.error(e,e);
			return "FAIL";
		}
		return "SUCCESS";
	}
	
	/**
	 * 以下为get ; set 方法
	 * @return
	 */
	public GoodsType getGoodsType() {
		return goodsType;
	}
	public void setGoodsType(GoodsType goodsType) {
		this.goodsType = goodsType;
	}
	public PackingFlow getPackingFlow() {
		return packingFlow;
	}
	public void setPackingFlow(PackingFlow packingFlow) {
		this.packingFlow = packingFlow;
	}
	public PackingType getPackingType() {
		return packingType;
	}
	public void setPackingType(PackingType packingType) {
		this.packingType = packingType;
	}
	public BoxProduct getBoxProduct() {
		return boxProduct;
	}
	public void setBoxProduct(BoxProduct boxProduct) {
		this.boxProduct = boxProduct;
	}
	public ParticleProduct getParticleProduct() {
		return particleProduct;
	}
	public void setParticleProduct(ParticleProduct particleProduct) {
		this.particleProduct = particleProduct;
	}
	public SemiFinishedProductPackage getSemifinishedProductPackage() {
		return semifinishedProductPackage;
	}
	public void setSemifinishedProductPackage(
			SemiFinishedProductPackage semifinishedProductPackage) {
		this.semifinishedProductPackage = semifinishedProductPackage;
	}
	public void setRequest(Map<String, Object> req) {
		this.req = req;
	}
	public String getProcess0() {
		return process0;
	}
	public void setProcess0(String process0) {
		this.process0 = process0;
	}
	public String getProcess1() {
		return process1;
	}
	public void setProcess1(String process1) {
		this.process1 = process1;
	}
	public String getProcess2() {
		return process2;
	}
	public void setProcess2(String process2) {
		this.process2 = process2;
	}
	public String getProcess3() {
		return process3;
	}
	public void setProcess3(String process3) {
		this.process3 = process3;
	}
	public String getProcess4() {
		return process4;
	}
	public void setProcess4(String process4) {
		this.process4 = process4;
	}
	public int getSelected() {
		return selected;
	}
	public void setSelected(int selected) {
		this.selected = selected;
	}
	@SuppressWarnings("unchecked")
	public List getCheckboxPar() {
		return checkboxPar;
	}
	@SuppressWarnings("unchecked")
	public void setCheckboxPar(List checkboxPar) {
		this.checkboxPar = checkboxPar;
	}
	public String getParticalNums() {
		return particalNums;
	}
	public void setParticalNums(String particalNums) {
		this.particalNums = particalNums;
	}
	public String getDeviceName() {
		return deviceName;
	}
	public void setDeviceName(String deviceName) {
		this.deviceName = deviceName;
	}
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}
